import requests
import zipfile
import os
import shutil

EdgeBetaPath = "C:\\Program Files (x86)\\Microsoft\\Edge Beta\\Application"
EdgePath = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application"

def downloadFromUrlToFile(url, File):
    """从url下载一个文件到给定的文件名中,下载失败则raise错误"""
    print(f"from {url} downloading:\n\t{File}")
    r = requests.get(url, allow_redirects=True, verify=False)
    if r.ok:
        with open(File, 'wb') as f:
            f.write(r.content)
        print(f"download done")
    else:
        print(f"download failed! {r}")
        raise Exception(f"download failed! {r}")

def downloadEdict()->str:
    """下载最新的的E_dict"""
    url1 = "https://gitee.com/umekoo/xmu_-daily_-health_-reporter/releases/download/newest/E_dict.json5"
    url2 = "https://github.com/umeiko/XMU_Reporter/releases/download/XMU2.0/E_dict.json5"
    
    r = requests.get(url1, allow_redirects=True)
    if not r.ok:
        r = requests.get(url2, allow_redirects=True)
    if r.ok:
        with open("E_dict.json5", 'wb') as f:
            f.write(r.content)
        return "download done"
    else:
        return f"download failed :{r}"
    

def confirmEdgeVersion(Path):
    """获取浏览器的版本号"""
    versions = []
    try:
        dir_items = os.scandir(Path)
        for item in dir_items:
            if item.is_dir():
                name = item.name
                if name.find(".") != -1:
                    versions.append(name)
    except:
        print(f"无此浏览器: {Path}")
    return versions

def confirmDriver():
    """获取存储的驱动版本"""
    Edge_versions = []
    EdgeBeta_versions = []
    try:
        os.mkdir(".\\Drivers")
    except BaseException:
        pass
    dir_items = os.scandir(".\\Drivers")
    for item in dir_items:
        name = item.name
        driver_type, driver_version = name.split("_")[:2]
        if driver_type == "EDGE":
            Edge_versions.append(driver_version[:-4])
        if driver_type == "EDGE BETA":
            EdgeBeta_versions.append(driver_version[:-4])
    return Edge_versions, EdgeBeta_versions

def unzipDriver(zip_file, out_file_name):
    """解压出驱动"""
    print(f"Unziping {zip_file}")
    with zipfile.ZipFile(zip_file) as zip_object:
        for f in zip_object.namelist():
            if f == "msedgedriver.exe":
                zip_object.extract(f, f".\\Drivers\\_{out_file_name}")
    print("driver installing done, cleaning...")
    shutil.move(f".\\Drivers\\_{out_file_name}\\msedgedriver.exe", f".\\Drivers\\{out_file_name}.exe")
    shutil.rmtree(f".\\Drivers\\_{out_file_name}")
    os.remove(zip_file)
    print("done")


def DownloadAndInstallDriver(version, edgeType):
    """下载安装需要的驱动"""
    driverUrl = f'https://msedgedriver.azureedge.net/{version}/edgedriver_win64.zip'
    zip_file  = f".\\Drivers\\_{edgeType}_{version}.zip"
    downloadFromUrlToFile(driverUrl, zip_file)
    unzipDriver(zip_file, f"{edgeType}_{version}")

def driver_check():
    """查询驱动的安装情况"""
    edgeTypes = ["EDGE", "EDGE BETA"]
    versions  = [confirmEdgeVersion(i) for i in [EdgePath, EdgeBetaPath]]
    drivers   = confirmDriver()
    driver_need = {"EDGE":[],
                   "EDGE BETA":[]}
    for anyEdgeVersion, anyEdgeDrivers, anyEdgeType in zip(versions, drivers, edgeTypes):
        if len(anyEdgeVersion) > 1:
            print(f"{anyEdgeType} should be reboot")
        for version in anyEdgeVersion:
            if version not in anyEdgeDrivers:
                driver_need[anyEdgeType].append(version)
    return driver_need

def getUseableDriverPath():
    """提供可用的驱动"""
    edgeTypes = ["EDGE", "EDGE BETA"]
    versions  = [confirmEdgeVersion(i) for i in [EdgePath, EdgeBetaPath]]
    drivers   = confirmDriver()
    driver_path = {"EDGE":[],
                   "EDGE BETA":[]}
    for anyEdgeVersion, anyEdgeDrivers, anyEdgeType in zip(versions, drivers, edgeTypes):
        if len(anyEdgeVersion) > 1:
            print(f"{anyEdgeType} should be reboot")
        for version in anyEdgeVersion:
            if version in anyEdgeDrivers:
                driver_path[anyEdgeType].append(f".\\Drivers\\{anyEdgeType}_{version}.exe")
    return driver_path

def clearUnusedDriver():
    """清理不需要的旧驱动"""
    edgeTypes = ["EDGE", "EDGE BETA"]
    versions  = [confirmEdgeVersion(i) for i in [EdgePath, EdgeBetaPath]]
    drivers   = confirmDriver()
    for anyEdgeVersion, anyEdgeDrivers, anyEdgeType in zip(versions, drivers, edgeTypes):
        for version in anyEdgeDrivers:
            if version not in anyEdgeVersion:
                os.remove(f".\\Drivers\\{anyEdgeType}_{version}.exe")

def main():
    """更新并查询驱动"""
    down_list = driver_check()
    driver_changed = {"EDGE":[],
                   "EDGE BETA":[]}
    if not down_list:
        print("Drivers Found !")
    else:
        for anyEdge in down_list:
            if down_list[anyEdge]:
                print(f"{anyEdge} driver need update.")
            else:
                print(f"No {anyEdge} driver need update.")
            for version in down_list[anyEdge]:
                DownloadAndInstallDriver(version, anyEdge)
                driver_changed[anyEdge].append(version)
    return driver_changed

if __name__ == "__main__":
    main()
    print(getUseableDriverPath())
    clearUnusedDriver()
    os.system("pause")